// $URL: http://mingw-lib.googlecode.com/svn/trunk/working/avcodec_to_widget_8/t_box_input_http.cpp $
// $Rev: 298 $
// $Author: akio.miyoshi $
// $Date:: 2010-07-28 14:12:27 +0000#$

#include "t_box_input_http.h"
#include "nbr.h"

class T_Box_Input_HttpPrivate
{
public:
    T_Box_Input_HttpPrivate(T_Box_Input_Http *q)
        : q_ptr(q)
        , m_buffer(new quint8[q->c_buffer_size])
        , m_seq(q->m_reply)
        , m_is_valid(false)
    {
    }
    ~T_Box_Input_HttpPrivate()
    {
        delete [] m_buffer;
    }
    Q_DECLARE_PUBLIC(T_Box_Input_Http)
    class T_Box_Input_Http *q_ptr;
    quint8 *m_buffer;
    NetworkSequence m_seq;
    bool m_is_valid;
};

T_Box_Input_Http::T_Box_Input_Http(QNetworkReply *a_reply)
    : m_reply(a_reply)
{
    this->d_ptr = new T_Box_Input_HttpPrivate(this);
    Q_D(T_Box_Input_Http);
    d->m_is_valid = true;
}

T_Box_Input_Http::~T_Box_Input_Http()
{
    delete m_reply;
    delete d_ptr;
}

bool T_Box_Input_Http::isValid()
{
    Q_D(T_Box_Input_Http);
    return d->m_is_valid;
}

void T_Box_Input_Http::close()
{
    Q_D(T_Box_Input_Http);
    //FIXME
    d->m_is_valid = false;
}

quint8* T_Box_Input_Http::getIOBuffer()
{
    //FIXME: buffer allocation should be handled by super class. sub class returns buffer size only.
    Q_D(T_Box_Input_Http);
    return d->m_buffer;
}

int T_Box_Input_Http::getIOBufferSize()
{
    return c_buffer_size;
}

int T_Box_Input_Http::read_bytes(uint8_t *buf, int buf_size)
{
    Q_D(T_Box_Input_Http);
    QByteArray v_bytes = d->m_seq.wait_read(buf_size);
    Q_ASSERT(v_bytes.size()<=buf_size);
    memcpy(buf, v_bytes.data(), v_bytes.size());
    return v_bytes.size();
}

int64_t T_Box_Input_Http::seek_getpos()
{
    Q_D(T_Box_Input_Http);
    return d->m_seq.pos();
}

int64_t T_Box_Input_Http::seek_setpos(int64_t offset)
{
    Q_D(T_Box_Input_Http);
    if(d->m_seq.seek(offset))
    {
        return d->m_seq.pos();
    }
    qDebug() << "(!d->m_seq.seek(offset))" << offset << d->m_seq.size();
    return -1;
}

int64_t T_Box_Input_Http::seek_length()
{
    Q_D(T_Box_Input_Http);
    return d->m_seq.size();
}
